<template>
	<view>
		<view class="article-content u-flex u-row-right">
      <view v-if="enableSubscribeMessage == 1 && activitySubscribeInfo.state == 1 && showSubscribeIcon" class="item u-flex" @click.stop="articleTap('subscribe')">
        <view class="macallan-icon" :class="haveSubscribed ? 'mcl-icondingyue' : 'mcl-icondingyue1'"></view>
        <view class="absolute">{{haveSubscribed ? '已订阅' : '订阅'}}</view>
      </view>
      <view v-if="enableLike == 1" class="item u-flex" @click.stop="articleTap('isLike')">
        <view class="macallan-icon" :class="isLike ? 'mcl-icondianzan': 'mcl-icondianzan1'"></view>
        <view class="absolute">{{likeCount}}</view>
      </view>
      <view v-if="enableShare == 1" class="item">
        <button class="u-flex" style="padding:0; background-color:#fff;" open-type="share">
          <view class="macallan-icon mcl-iconfenxiang"></view>
          <view class="absolute">分享</view>
        </button>
      </view>
    </view>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
	</view>
</template>

<script>
  import api from '@/api/api';
  import util from '@/utils/util';
  import { CART_KEY, USER_INFO, SYSTEM_INFO, MEMBER_INFO, CUSTOMER_INFO, MERCHANT_INFO, USER_SPECICAL_INFO } from '@/utils/constant';
	export default {
		name:"articleSubscribe",
    props:{
      userLogin:Boolean,
      pathOption:String,
      pageId:Number,
      enableSubscribeMessage:{
        default: 0,
        type: Number,
      },
      enableLike:{
        default: 0,
        type: Number,
      },
      enableShare:{
        default: 0,
        type: Number,
      },
      activitySubscribeId: {
        type: Number,
        default: 32,
      },
    },
		data() {
			return {
        defaultShareImage: 'https://100000063-1252208446.cos.ap-shanghai.myqcloud.com/images/miniprogram/inviteforward/2022021505515.jpg',
        shareImage: '', // CMS动态转发图片
        showSubscribeIcon: true,
        likeContent:[],
        activitySubscribeInfo: {},
        haveSubscribed: false,
        isLike: false,
        likeCount: 0,
        type: 'articleSubscribe',
			};
		},
    created() {
      let  that = this;
      if(that.enableSubscribeMessage == 1) {
        that.getSubscribeInfo()
      }
      if(that.enableLike == 1) {
        that.articleLikeInfo(that.pageId)
      }
    },
    methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
      articleTap(val){
        let that = this
        if(val == 'subscribe'){
          if(this.haveSubscribed) {
            this.handleShowTextToast('已订阅')
            return
          } else {
            if(that.userLogin) {
              that.requestSubscribe(this.activitySubscribeId, that.activitySubscribeInfo.templateId, that.activitySubscribeInfo.pageAfterSubscribe, '', this.type)
            } else {
              this.$emit('registerTap', {  //传到父组件registerStatus方法里把clickType传过去确定是点赞事件，把接口里的islike字段传过去判断是否点赞
                 'clickType': val,
              })
            }
          }
        } else if(val == 'isLike'){
          that.articleGood(that.pageId)
        }
      },

      requestSubscribe: function(activitySubscribeId, templateId, pageAfterSubscribe, activitySubscribeNavigate, type){
        let that = this;
        let tmplIds = [];
        tmplIds.push(templateId)
        that.$commonSensors.popupEvent('PopupExposure', {'popup_type' : '订阅消息', 'popup_name': '订阅消息弹窗'})
        that.$commonSensors.modelAuthAsk('文章', tmplIds)
        uni.requestSubscribeMessage({
          tmplIds: tmplIds,
          success(res) {
            if(res[templateId] == "accept") { // 用户允许接收订阅消息
              util.doSubscribe(activitySubscribeId, pageAfterSubscribe, activitySubscribeNavigate, type).then((res)=> {
                if(res.code == 1000) {
                  that.handleShowTextToast('订阅成功')
                  that.haveSubscribed = true;
                  if(!pageAfterSubscribe) {
                    return
                  } else {
                    uni.navigateTo({
                      url: `/${pageAfterSubscribe}`
                    })
                  }
                } else {
                  that.haveSubscribed = false;
                  that.handleShowTextToast("订阅失败")
                }
              })
              that.$commonSensors.popupEvent('PopupClick', {'popup_type' : '订阅消息', 'popup_name': '订阅消息弹窗', 'button_name': '允许'})
            } else {
              that.$commonSensors.popupEvent('PopupClick', {'popup_type' : '订阅消息', 'popup_name': '订阅消息弹窗', 'button_name': '拒绝'})
            }
          },
          fail(res){
          },
          complete(res) {
          }
        });
      },

      getSubscribeInfo(){
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || '';
        // 需求未登录用户也能订阅, 测试通过后可删
        // if(!customerInfo && !that.userLogin) {
        //   that.activitySubscribeInfo.state = 1;
        //   that.showSubscribeIcon = true;
        //   return
        // }
        util.getActivitySubscribeDetail(this.activitySubscribeId, '', this.type).then((res)=>{
          if(res) {
            if(res.code == 1000) {
              that.activitySubscribeInfo = res.data;
              if(res.data.type === "auto") {
                let nowTime = new Date().getTime() / 1000;
                let planSendTime = new Date(res.data.planSendTime.replace(/-/g, '/' )).getTime() / 1000
                if(nowTime - planSendTime > 0) {
                  that.showSubscribeIcon = false
                  return
                }
              }
              if(res.data.state !== 0) {
                util.getCustomerSubscribeInfo(this.activitySubscribeId, '', '', '', this.type).then((result)=> {
                  if(result.code == 1000) {//已订阅
                    that.haveSubscribed = true;
                    return
                  } else {
                    that.haveSubscribed = false;
                  }
                })
              }
            } else {
              that.showSubscribeIcon = false
            }
          }
        })
      },

      //更新点赞
    articleGood: async function(pageId){
      let that = this
      let userSpecialInfo = uni.getStorageSync(USER_SPECICAL_INFO) || ''
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
      let entityId = String(pageId)
      let likeType = "";
      if(this.isLike) {
        likeType = "cancel"
      } else {
        likeType = "like"
      }
      const result = await api.articleGood({
        method: 'POST',
        query:{
          "merchantId": merchantInfo.cloudMerchantId,
          "storeId": merchantInfo.cloudMerchantStoreId,
          "entityType": "ARTICLE",
          "entityId":entityId,
          "userId": userSpecialInfo.openid,
          "userType": "openId",
          "likeCountType": "UV",
          "likeType": likeType,
         }
       })
        if(result.code == 1000){
          if(this.isLike) {
            this.handleShowTextToast('已取消点赞')
            if(this.likeCount == 0) {
              this.likeCount = 0
            } else {
              this.likeCount--
            }
            this.isLike = !this.isLike;
          } else {
            this.handleShowTextToast('点赞成功')
            this.likeCount++
            this.isLike = !this.isLike;
          }
        }else{
          this.handleShowTextToast('点赞失败')
        }
      },

      //点赞信息
      articleLikeInfo: async function(pageId){
        let that = this
        let userSpecialInfo = uni.getStorageSync(USER_SPECICAL_INFO) || ''
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
        let entityId = String(pageId)
        const result = await api.articleLikeInfo({
          method: 'GET',
          query:{
            "merchantId": merchantInfo.cloudMerchantId,
            "storeId": merchantInfo.cloudMerchantStoreId,
            "entityType": "ARTICLE",
            "entityId":entityId,
            "userId": userSpecialInfo.openid,
            "userType": "openId",
            "likeCountType": "UV",
          }
        })
        if(result.code == 1000){
          this.likeCount = result.data.count;
          this.isLike = result.data.isLike;
        }else {
          // this.handleShowTextToast('未获取点赞数量');
        }
      },


      //点赞总数
      articleGoodTotal: async function(pageId){
        let that = this
        let userSpecialInfo = uni.getStorageSync(USER_SPECICAL_INFO) || ''
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
        let entityIds = [];
        entityIds.push(JSON.stringify(pageId))
        let params = {
          "customerUniqueId": "",
          "entityIds":entityIds,
          "entityType": "ARTICLE",
          "extInfo": "",
          "likeCountType": "UV",
          "merchantId": merchantInfo.cloudMerchantId,
          "openId": userSpecialInfo.openid,
          "storeId": merchantInfo.cloudMerchantStoreId,
          "unionId": userSpecialInfo.unionId,
        }
        // return
        const articleGoodTotal = await api.articleLikeList({
          method: 'GET',
          query:params
        })
         if(articleGoodTotal.code == 1000){
           this.likeContent = articleGoodTotal.data
         }else {
          // this.handleShowTextToast('未获取点赞数量');
        }
      },

      onShareAppMessage(res) {
        let path = 'pages/cms/page?identifier=' + this.pathOption
        let shareImg = this.shareImage || this.defaultShareImage
        let shareTitle = uni.getStorageSync('storeName') || '小程序商城'
        this.$commonSensors.sensorsPageShare()
				this.$sr.setContext({ share_title: shareTitle });
        return this.$commonFunction.commonShare(res, shareTitle, path, shareImg);
      },
    }
	}
</script>

<style lang="less">
.article-content{
      border-top: 2rpx solid #f7f5f4;
      width: 100%;
  .item{
    height: 100rpx;
    margin-right: 60rpx !important;
    display: flex;
    flex-direction: row;
    align-items: center;
  }

 .absolute{
    padding-left: 10rpx;

  }

}
.u-flex {
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -webkit-flex-direction: row;
    flex-direction: row;
    -webkit-box-align: center;
    -webkit-align-items: center;
    align-items: center;
}
.u-row-right {
    -webkit-box-pack: end;
    -webkit-justify-content: flex-end;
    justify-content: flex-end;
}
</style>
